package com.gitee.wsl.doc.prosemirror.collab

import com.gitee.wsl.doc.prosemirror.plugin.PluginSpec
import com.gitee.wsl.doc.prosemirror.plugin.StateField
import com.gitee.wsl.doc.prosemirror.state.EditorStateConfig
import com.gitee.wsl.doc.prosemirror.state.EditorState
import com.gitee.wsl.doc.prosemirror.state.Transaction

class CollabPluginSpec(conf: CollabConfig) : PluginSpec<CollabState>() {
    override val key = collabKey
    override val state: StateField<CollabState> = object : StateField<CollabState> {
        override fun init(config: EditorStateConfig, instance: EditorState): CollabState {
            return CollabState(conf.version, emptyList())
        }

        override fun apply(
            tr: Transaction,
            value: CollabState,
            oldState: EditorState,
            newState: EditorState
        ): CollabState {
            val state = tr.getMeta(collabKey)
            return when {
                state != null -> state as CollabState
                tr.docChanged -> CollabState(value.version, value.unconfirmed + unconfirmedFrom(tr))
                else -> value
            }
        }
    }

    override val additionalProps: Map<String, Any> = mapOf(
        "config" to conf,
        // This is used to notify the history plugin to not merge steps,
        // so that the history can be rebased.
        "historyPreserveItems" to true
    )

    val config: CollabConfig by additionalProps
    val historyPreserveItems: Boolean by additionalProps
}